# -*- coding: UTF-8 -*-

from django.views.decorators.csrf import csrf_exempt
from django.views.generic.list_detail import object_detail, object_list
from django.views.generic.create_update import update_object, create_object, delete_object
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.contrib.messages import info, error

from PidaRestauranteWeb.nucleo.models import *
from PidaRestauranteWeb.nucleo.forms import *

@csrf_exempt
def funcionario_list(request, page):
    query_set = Funcionario.objects.filter(user__is_active = True)
    return object_list(
                       request = request,
                       queryset = query_set,
                       paginate_by = 15,
                       page = page,
                       template_name = 'generic_list.html',
                       extra_context = {'title':u'Lista de Funcionários',
                                        'link':'nucleo/funcionario',
                                        }
                       )

@csrf_exempt
def funcionario_create(request):
    if request.method == 'POST':
        form = FuncionarioForm(request.POST)
        if form.is_valid():
            try:
                user = User.objects.create_user(form.cleaned_data['nome'], form.cleaned_data['email'], '123456')
                funcionario = Funcionario()
                funcionario.user = user
                funcionario.cargo = form.cleaned_data['cargo']
            except:
                error(request, u'Houve alguma incompatibilidade no cadastro. Verifique se este já existe.')
                return render_to_response('generic_form.html',
                              {'form':form,
                               'title':u'Cadastro de Funcionário',},
                              context_instance=RequestContext(request))
            else:
                user.save()
                funcionario.save()
                info(request, u'Cadastro de Funcionário')
                return HttpResponseRedirect('/nucleo/funcionario/page1')
        return render_to_response('generic_form.html',
                              {'form':form},
                              context_instance=RequestContext(request))
    form = FuncionarioForm()
    return render_to_response('generic_form.html',
                              {'form':form,
                               'title':u'Cadastro de Funcionário',},
                              context_instance=RequestContext(request))

@csrf_exempt
def funcionario_update(request, object_id):
    object = Funcionario.objects.get(id=object_id)
    if request.method == 'POST':
        form = FuncionarioForm(request.POST, initial={'nome':object.user.username, 'email':object.user.email, 'cargo':1})
        if form.is_valid():
            try:
                user = object.user
                user.username = form.cleaned_data['nome']
                user.email = form.cleaned_data['email']
                object.cargo = form.cleaned_data['cargo']
            except:
                error(request, u'Houve alguma incompatibilidade no cadastro. Verifique se este já existe.')
                return render_to_response('generic_form.html',
                              {'form':form,
                               'title':u'Cadastro de Funcionário',},
                              context_instance=RequestContext(request))
            else:
                user.save()
                object.save()
                info(request, u'Cadastro de Funcionário')
                return HttpResponseRedirect('/nucleo/funcionario/page1')
        return render_to_response('generic_form.html',
                              {'form':form},
                              context_instance=RequestContext(request))
    form = FuncionarioForm(initial={'nome':object.user.username, 'email':object.user.email, 'cargo':1})
    return render_to_response('generic_form.html',
                              {'form':form,
                               'title':u'Atualizar cadastro de funcionário',},
                              context_instance=RequestContext(request))
    
@csrf_exempt
def funcionario_remove(request, object_id):
    if request.method == 'POST':
        object = Funcionario.objects.get(id = object_id)
        user = object.user
        user.is_active = False
        user.save()
        info(request, u'Desativado com sucesso.')
    return HttpResponseRedirect('/nucleo/funcionario/page1')

def todo(request):
    info(request, u"Funcionalidade ainda não implementada!")
    return HttpResponseRedirect('/')